<template>
  <page-wrap ref="pageWrap" hideTab back :title="title" :stayStill="stayStill" bgColor="white" :showTop="showTop"
    :dark="loaded ? false : true" :hideSafeArea="true">
    <view :class="['wrapper']">
      <!-- <block v-if="rightId == 100">
        <view class="content">
          <template v-for="(item, index) in imgListMapper[rightId] || []">
            <image mode="widthFix" style="width: 100vw" :src="item" :key="index"> </image>
          </template>
        </view>
        <view class="pageTextContainer">
          <text class="textTitle">{{ rightProductDetail.product.name }}</text>
          <text class="textSubTitle">{{ rightProductDetail.product.subTitle }}</text>
          <text class="textDescTitle">服务介绍：</text>
          <text class="textDesc">{{ rightProductDetail.product.description }}</text>
        </view>
      </block>
      <block v-else> -->
        <view class="content">
          <template v-for="(item, index) in imgLists || []">
            <image mode="widthFix" style="width: 100vw" :src="item" :key="index"> </image>
          </template>
        </view>
      <!-- </block> -->
      <view class="bottomBtn" @click="handleBottomBtnClick">
        <view class="textContainer">
          <view class="btnText">新春特惠<text class="rmb">¥ </text> <text class="priceNum">{{
            rightProductDetail.product.price
              }}</text>/份 </view>
          <view class="slashText">原价¥{{ rightProductDetail.product.originalPrice }}</view>
        </view>
      </view>
    </view>
    <LoginDialog ref="loginDialog" @loginSuccessBack="loginSuccessBack"></LoginDialog>
  </page-wrap>
</template>

<script>
// import { env } from '@/api/root';
import { getCVM1001ProductDetail, addCartAndToOrder, addZhituPayOrder, getCVM1001OrderDetail, upportCVM1001OrderDetail, getCVM1001PayPage } from '@/api/modules/career';
import LoginDialog from '@/components/LoginDialog';
export default {
  components: {
    LoginDialog,
  },
  data() {
    return {
      personId: uni.getStorageSync('person-id').slice(2) || undefined,
      dataResourceId: '', //数据资产id
      orderId: '', //订单id
      orderSn: '', //订单编号
      payOrderId: '', //支付订单id
      productId: '13657', //商品ID,生产&预发布环境：13657，测试环境：1583
      rightProductDetail: {},

      title: '',
      navHeight: getApp().globalData.navHeight,
      rightId: 100,
      stayStill: false, //顶部是否自己占位置
      showTop: false, //顶部是否透明
      //mapper以rightId作为键值
      //根据不同的rightId展示不同的样式，背景图

      imgListMapper: {
        100: [this.$imgBase + 'cvm1001/cvmPayPageBG2_3x.png'],
      },
      imgLists: [],
      titleText: "",
      provider: {},
    };
  },

  created() {
    uni.showLoading({
      title: '获取服务信息中...',
      mask: true,
    });
    //获取支付提供商
    uni.getProvider({
      service: 'payment',
      success: (res) => {
        this.provider = res.provider;
      },
      complete: (res) => {
        uni.hideLoading();
      },
    });
  },

  onPageScroll(e) {
    //滚动改变颜色
    if (e.scrollTop >= 64) {
      this.showTop = true;
      this.title = this.titleText;
    } else {
      this.showTop = false;
      this.title = '';
    }
  },

  onLoad(opt) {
    //console.log('----opt:', opt);
    this.dataResourceId = opt.dataResourceId;
    this.personId = opt.personId;

    this.getProductDetail();
    this.getPageInfo();

    //简历诊断时特殊处理
    if (opt.rightId == 4) {
      this.stayStill = true;
      this.showTop = true;
      this.title = '简历诊断';
      this.navHeight = 0;
    }
  },
  mounted() { },

  methods: {
    //获取商品信息展示用
    getProductDetail() {
      getCVM1001ProductDetail({
        productId: this.productId
      })
        .then((res) => {
          this.rightProductDetail = res.data;
        })
        .finally(() => {
          uni.hideLoading();
        });
    },

    getPageInfo() {
      uni.showLoading({
        title: '页面加载中...',
        mask: true,
      });
      getCVM1001PayPage({
        dataResourceId: this.dataResourceId, // "1394"
      })
        .then((res) => {
          if (res.code == 200) {
            this.titleText = res.data.paymentTopTitle;
            this.imgLists = res.data.paymentImgOSSLinkList;
          } else {
            uni.showToast({
              title: res.status_desc || '页面加载失败',
              icon: 'none',
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          uni.showToast({
            title: err.status_desc || '页面加载失败',
            icon: 'none',
            duration: 2000,
          });
        })
        .finally(() => {
          uni.hideLoading();
        });
    },

    // 底部按钮点击事件
    handleBottomBtnClick() {
      if (!this.personId) {
        this.showLoginDialog();
        return;
      }

      // 先不订阅，直接下一步
      //this.handlePaySubscribe();
      // 直接生成订单
      this.addCartAndToOrder();
    },

    // 登录事件
    showLoginDialog() {
      this.$refs.loginDialog.setVisibility(true);
    },
    // 登录成功回调
    loginSuccessBack() {
      this.personId = uni.getStorageSync('person-id').slice(2) || undefined;
    },

    //1.生成订单
    addCartAndToOrder() {
      //上报提交职途订单事件
      // wx.reportEvent('submit_career_path_order', {});

      uni.showLoading({
        title: '生成订单中...',
        mask: true,
      });
      addCartAndToOrder({
        orderType: 'CVM_1001_H5', //订单类型：1001CVMH5
        channelType: 83, //订单渠道来源
        sourceType: 3, //订单来源：0:pc 1:安卓 2:ios 3:小程序
        mallProductId: this.productId,
        personId: this.personId, //人才ID
        personName: uni.getStorageSync('personName'), //人才名称
      })
        .then((res) => {
          if (res.code == 200) {
            this.orderId = res.data.orderId;
            this.orderSn = res.data.orderSn;
            this.addZhituPayOrder(res.data);
          } else {
            uni.hideLoading();
            uni.showToast({
              title: res.status_desc || '生成订单失败',
              icon: 'none',
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          uni.hideLoading();
          uni.showToast({
            title: err.status_desc || '生成订单失败',
            icon: 'none',
            duration: 2000,
          });
        })
        .finally(() => { });
    },
    //2.通过订单获取支付信息
    addZhituPayOrder(data) {
      addZhituPayOrder({
        ...data,
        orderType: 'CVM_1001_H5', //1001CVM榜单类型
        wayCode: 'WX_LITE', // 固定
        personId: this.personId, //人才id
        personName: uni.getStorageSync('personName'), //人才名称
        openid: uni.getStorageSync('openid'), //当前人才绑定的openId
      })
        .then((res) => {
          if (res.code == 200) {
            this.payOrderId = res.data.payOrderId;
            this.requestPayment(res.data);
            this.requestOrderReport();
          } else {
            uni.hideLoading();
            uni.showToast({
              title: res.status_desc || '获取商品信息失败',
              icon: 'none',
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          uni.hideLoading();
          uni.showToast({
            title: err.status_desc || '获取商品信息失败',
            icon: 'none',
            duration: 2000,
          });
        })
        .finally(() => { });
    },
    //3.使用支付信息调用支付
    requestPayment(data) {
      uni.hideLoading();
      if (this.provider.indexOf('wxpay') < 0) {
        return;
      }
      const payData = JSON.parse(data.payData);
      uni.requestPayment({
        provider: this.provider[0],
        timeStamp: payData.timeStamp,
        nonceStr: payData.nonceStr,
        package: payData.package,
        signType: payData.signType,
        paySign: payData.paySign,
        success: (res) => {
          this.requestOrderDetail(data.payOrderId);
        },
        fail: (err) => {
          uni.showToast({
            title: '支付失败,请您重新支付',
            icon: 'none',
            duration: 3000,
          });
        },
      });
    },
    //4.支付成功后跳转到订单详情页
    requestOrderDetail(payOrderId) {
      uni.showLoading({
        title: '核对订单中...',
        mask: true,
      });
      getCVM1001OrderDetail({
        payOrderId: payOrderId,
      })
        .then((res) => {
          uni.hideLoading();
          if (res.code == 200) {
            let disc = '';
            const state = res.data.state;
            if (state == 2) {
              disc = '支付成功';
            } else if (state == 3) {
              disc = '支付失败';
            } else if (state == 4) {
              disc = '已撤销';
            } else if (state == 5) {
              disc = '已退款';
            } else if (state == 6) {
              disc = '订单关闭';
            } else {
              disc = '支付取消'; // 0-订单生成, 1-支付中,
            }
            uni.showModal({
              title: disc,
              content: '确定要离开当前页面吗？',
              confirmText: "确定",
              confirmColor: "#E18831",
              cancelText: "取消",
              success: (res) => {
                if (res.confirm) {
                  uni.exitMiniProgram();
                } else if (res.cancel) {
                  // 用户点击了取消，不做任何事情
                }
              }
            });
          } else {
            uni.showToast({
              title: res.status_desc || '核对订单失败',
              icon: 'none',
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          uni.hideLoading();
          uni.showToast({
            title: err.status_desc || '核对订单失败',
            icon: 'none',
            duration: 2000,
          });
        })
        .finally(() => { });
    },

    //5.上报订单
    requestOrderReport() {
      upportCVM1001OrderDetail({
        dataResourceId: this.dataResourceId, //数据资产id，h5跳转时携带
        personId: this.personId, //人才id，h5跳转时携带
        orderId: this.orderId, //订单id
        orderSn: this.orderSn, //订单编号
        payOrderId: this.payOrderId, //支付订单号
      })
        .then((res) => {
          if (res.code == 200) {
            console.log('--- - 成功上报订单');
          } else {
            console.log('--- - 失败上报订单');
          }
        })
        .catch((err) => {
          console.log('--- - 失败上报订单');
        })
        .finally(() => { });
    },
  },
};
</script>

<style lang="scss" scoped>
$img-base-careerPath: $img-base + 'careerPath/';

@font-face {
  font-family: 'D-DIN-PRO-700-Bold';
  /*定义字体名称*/
  src: url('https://img3.job1001.com/ypMp/elan/images/career/positionDictionary/D-DIN-PRO-700-Bold.ttf');
}

@font-face {
  font-family: 'D-DIN-PRO-500-Medium';
  /*定义字体名称*/
  src: url('https://img3.job1001.com/ypMp/elan/fontFamily/careerPath/D-DIN-PRO-500-Medium.otf');
}

.wrapper {
  height: 100vh;
  // background: linear-gradient(180deg, #e8f9ff 0%, #f4f6f8 100%);
  // background-image: url("https://img3.job1001.com/ypMp/elan/images/careerPath/zhituPayBG.png?v=1");
  background-repeat: no-repeat;
  background-size: 100% 100%;

  .content {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    width: 100vw;
    box-sizing: border-box;
  }

  .pageTextContainer {
    display: flex;
    flex-direction: column;
    padding: 0 26px;
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 9;

    .textTitle {
      font-size: 32px;
      font-weight: 600;
      color: #222;
      margin-top: 120px;
      line-height: 45px;
      font-family: PingFangSC, PingFang SC;
    }

    .textSubTitle {
      font-size: 16px;
      color: #54585A;
      margin-top: 12px;
      line-height: 22px;
      font-weight: 600;
      font-family: PingFangSC, PingFang SC;
    }

    .textDescTitle {
      height: 22px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 600;
      font-size: 16px;
      color: #54585A;
      line-height: 22px;
      margin-top: 284px;
    }

    .textDesc {
      font-size: 14px;
      color: #616567;
      margin-top: 20px;
      font-weight: 400;
      font-family: PingFangSC, PingFang SC;
    }
  }

  .bottomBtn {
    position: fixed;
    bottom: 76rpx;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    // padding-left: 124rpx;
    width: calc(100vw - 80rpx);
    height: 100rpx;
    margin: 0 40rpx;
    z-index: 999;
    background: #ff711e;
    border-radius: 200rpx;
    background-image: url($img-base-careerPath + 'zhituPaybottomBtnBG.png');
    background-repeat: no-repeat;
    background-size: 100% 100%;

    .textContainer {
      display: flex;
      align-items: flex-end;

      .btnText {
        font-size: 32rpx;
        font-family: PingFang-SC, PingFang-SC;
        font-weight: 800;
        color: #ffffff;

        .rmb {
          display: inline-block;
          font-size: 26rpx;
          font-family: PingFang-SC, PingFang-SC;
          font-weight: bold;
          color: #ffe5cd;
          line-height: 40rpx;
          margin-left: 16rpx;
          margin-right: 10rpx;
        }

        .priceNum {
          font-family: D-DIN-PRO-700-Bold;
          font-size: 36rpx;
          font-family: D-DIN-PRO, D-DIN-PRO;
          font-weight: bold;
          color: #ffffff;
          line-height: 40rpx;
        }
      }

      .slashText {
        margin-left: 20rpx;
        font-size: 26rpx;
        font-family: PingFang-SC, PingFang-SC;
        font-weight: bold;
        color: #ffe5cd;
        line-height: 40rpx;
        text-decoration: line-through;
      }
    }
  }
}
</style>
